<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222"><meta name="generator" content="Hexo 5.4.2">

  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" integrity="sha256-HtsXJanqjKTc8vVQjO4YMhiqFoXkfBsjBWcX91T1jr8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"xiaoqingming18.github.io","root":"/","images":"/images","scheme":"Muse","darkmode":false,"version":"8.15.1","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":false,"style":null},"bookmark":{"enable":false,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"menu_item":"fadeInDown","post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"}}</script><script src="/js/config.js"></script>

    <meta name="description" content="构造函数构造函数介绍在JavaScript中，构造函数与普通函数是一样的，为了区分普通函数与构造函数，人为规定构造函数首字母要大写，并且构造函数不需要显式地return实例。下面是一个使用构造函数创建实例对象的例子： 12345678910function Person(name,age,job) {    this.name &#x3D; name;    this.age &#x3D; age;    this.">
<meta property="og:type" content="article">
<meta property="og:title" content="JavaScript：构造函数与原型、原型链">
<meta property="og:url" content="http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/index.html">
<meta property="og:site_name" content="鸣蜩十七">
<meta property="og:description" content="构造函数构造函数介绍在JavaScript中，构造函数与普通函数是一样的，为了区分普通函数与构造函数，人为规定构造函数首字母要大写，并且构造函数不需要显式地return实例。下面是一个使用构造函数创建实例对象的例子： 12345678910function Person(name,age,job) {    this.name &#x3D; name;    this.age &#x3D; age;    this.">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/三者关系.png">
<meta property="og:image" content="http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/继承运行结果1.png">
<meta property="og:image" content="http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/继承运行结果2.png">
<meta property="article:published_time" content="2023-07-16T05:50:27.000Z">
<meta property="article:modified_time" content="2023-07-16T09:04:21.182Z">
<meta property="article:author" content="鸣蜩十七">
<meta property="article:tag" content="-JavaScript基础 -构造函数 -原型 -原型链">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/三者关系.png">


<link rel="canonical" href="http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/","path":"2023/07/16/JavaScript：构造函数与原型、原型链/","title":"JavaScript：构造函数与原型、原型链"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>JavaScript：构造函数与原型、原型链 | 鸣蜩十七</title>
  








  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>

<style>.github-emoji { position: relative; display: inline-block; width: 1.2em; min-height: 1.2em; overflow: hidden; vertical-align: top; color: transparent; }  .github-emoji > span { position: relative; z-index: 10; }  .github-emoji img, .github-emoji .fancybox { margin: 0 !important; padding: 0 !important; border: none !important; outline: none !important; text-decoration: none !important; user-select: none !important; cursor: auto !important; }  .github-emoji img { height: 1.2em !important; width: 1.2em !important; position: absolute !important; left: 50% !important; top: 50% !important; transform: translate(-50%, -50%) !important; user-select: none !important; cursor: auto !important; } .github-emoji-fallback { color: inherit; } .github-emoji-fallback img { opacity: 0 !important; }</style>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <div class="column">
      <header class="header" itemscope itemtype="http://schema.org/WPHeader"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">鸣蜩十七</p>
      <i class="logo-line"></i>
    </a>
      <p class="site-subtitle" itemprop="description">鸣蜩十七是和女朋友谈恋爱的日子</p>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger" aria-label="搜索" role="button">
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li><li class="menu-item menu-item-schedule"><a href="/schedule/" rel="section"><i class="fa fa-calendar fa-fw"></i>日程表</a></li><li class="menu-item menu-item-sitemap"><a href="/sitemap.xml" rel="section"><i class="fa fa-sitemap fa-fw"></i>站点地图</a></li><li class="menu-item menu-item-commonweal"><a href="/404/" rel="section"><i class="fa fa-heartbeat fa-fw"></i>公益 404</a></li>
  </ul>
</nav>




</header>
        
  
  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0"><span class="nav-text">构造函数</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%BB%8B%E7%BB%8D"><span class="nav-text">构造函数介绍</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E5%AD%98%E5%9C%A8%E7%9A%84%E9%97%AE%E9%A2%98"><span class="nav-text">构造函数存在的问题</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E6%A8%A1%E5%BC%8F"><span class="nav-text">原型模式</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E5%AF%B9%E8%B1%A1"><span class="nav-text">原型对象</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#constructor%E5%B1%9E%E6%80%A7"><span class="nav-text">constructor属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#Prototype-%E7%89%B9%E6%80%A7%E4%B8%8E-proto-%E5%B1%9E%E6%80%A7"><span class="nav-text">[[Prototype]]特性与__proto__属性</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%BD%BB%E5%BA%95%E6%90%9E%E6%87%82prototype%E3%80%81constructor%E5%92%8C-proto-%E4%B9%8B%E9%97%B4%E7%9A%84%E5%85%B3%E7%B3%BB"><span class="nav-text">彻底搞懂prototype、constructor和__proto__之间的关系</span></a></li></ol></li><li class="nav-item nav-level-1"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E9%93%BE"><span class="nav-text">原型链</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#ES5%E7%BB%A7%E6%89%BF"><span class="nav-text">ES5继承</span></a><ol class="nav-child"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E7%BB%A7%E6%89%BF"><span class="nav-text">原型继承</span></a></li><li class="nav-item nav-level-2"><a class="nav-link" href="#%E5%8E%9F%E5%9E%8B%E7%BB%A7%E6%89%BF%E7%9A%84%E4%B8%BB%E8%A6%81%E9%97%AE%E9%A2%98"><span class="nav-text">原型继承的主要问题</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">鸣蜩十七</p>
  <div class="site-description" itemprop="description">记录我的学习、生活和恋爱日常</div>
</div>
<div class="site-state-wrap animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">43</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">8</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">37</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>

        </div>
      </div>
    </div>

    
  </aside>


    </div>

    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="http://xiaoqingming18.github.io/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="鸣蜩十七">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="鸣蜩十七">
      <meta itemprop="description" content="记录我的学习、生活和恋爱日常">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="JavaScript：构造函数与原型、原型链 | 鸣蜩十七">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          JavaScript：构造函数与原型、原型链
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>
      

      <time title="创建时间：2023-07-16 13:50:27 / 修改时间：17:04:21" itemprop="dateCreated datePublished" datetime="2023-07-16T13:50:27+08:00">2023-07-16</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/%E5%89%8D%E7%AB%AF/" itemprop="url" rel="index"><span itemprop="name">-前端</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h1 id="构造函数"><a href="#构造函数" class="headerlink" title="构造函数"></a>构造函数</h1><h2 id="构造函数介绍"><a href="#构造函数介绍" class="headerlink" title="构造函数介绍"></a>构造函数介绍</h2><p>在JavaScript中，构造函数与普通函数是一样的，为了区分普通函数与构造函数，人为规定构造函数首字母要大写，并且<strong>构造函数不需要显式地<code>return</code>实例</strong>。下面是一个使用构造函数创建实例对象的例子：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Person</span>(<span class="params">name,age,job</span>) {</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">name</span> = name;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">age</span> = age;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">job</span> = job;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="title function_">sayName</span>() = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">        <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">name</span>);</span><br><span class="line">    };</span><br><span class="line">}</span><br><span class="line"><span class="keyword">let</span> aMan = <span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">"小清明十八"</span>,<span class="number">20</span>,<span class="string">"前端炮灰"</span>);</span><br><span class="line">aMan.<span class="title function_">sayName</span>(); <span class="comment">// 小清明十八</span></span><br></pre></td></tr></tbody></table></figure>
<blockquote>
<p>构造函数不是只能用函数声明的形式，也可以将构造函数赋值给变量。</p>
<p>实例化时，构造函数后面的括号可加可不加。</p>
</blockquote>
<p>当时用<code>New</code>操作符创建实例对象时，调用构造函数会执行如下操作：</p>
<ol>
<li>在内存中创建一个对象。</li>
<li>这个新对象内部的<code>[[Prototype]]</code>（即<code>__proto__属性</code>）特性被赋值为构造函数的<code>prototype</code>属性。说人话就是新对象的<code>__proto__</code>属性指向原型对象。</li>
<li>构造函数内部的<code>this</code>被赋值为这个新对象，即<code>this</code>指向新对象。</li>
<li>执行构造函数内部的代码，即给新对象添加属性和方法。</li>
<li>隐式返回刚刚创建的新对象。</li>
</ol>
<blockquote>
<p>在构造函数中定义的属性和方法最终会添加到实例对象上！</p>
</blockquote>
<p>通过构造函数创建的每个实例对象都有一个<code>constructor</code>属性，指向构造函数。所以可以使用<code>instancof</code>操作符确定对象类型，比如在上面的例子中：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(aMan <span class="title function_">instanceof</span>(<span class="title class_">Person</span>)); <span class="comment">// true</span></span><br></pre></td></tr></tbody></table></figure>
<h2 id="构造函数存在的问题"><a href="#构造函数存在的问题" class="headerlink" title="构造函数存在的问题"></a>构造函数存在的问题</h2><p>构造函数存在的主要问题是，<strong>其定义的方法会在每个实例上都创建一遍，浪费内存</strong>。因此，同一个构造函数创建的不同实例对象的同名函数并不相等：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">let</span> person1 = <span class="keyword">new</span> <span class="title class_">Person</span>(···);</span><br><span class="line"><span class="keyword">let</span> person2 = <span class="keyword">new</span> <span class="title class_">Person</span>(···);</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(person1.<span class="property">sayName</span> == person2.<span class="property">sayName</span>); <span class="comment">// false</span></span><br></pre></td></tr></tbody></table></figure>
<p>这个问题可以通过下面要介绍的原型模式来解决。</p>
<h1 id="原型模式"><a href="#原型模式" class="headerlink" title="原型模式"></a>原型模式</h1><h2 id="原型对象"><a href="#原型对象" class="headerlink" title="原型对象"></a>原型对象</h2><p>无论何时，只要创建一个函数，就会按照特定的规则自动为这个函数创建一个<code>prototype</code>属性，这个属性是一个对象，称为<strong>原型对象</strong>，这个对象的作用是实现对象属性和方法的共享，这很好的解决了构造函数带来的内存浪费问题。因为<strong>原型对象包含由特定引用类型的实例共享的属性和方法</strong>。</p>
<p>我们可以将实例对象共有的属性和方法添加到构造函数对应的原型对象上面。例如前面的<code>Person</code>例子，我们可以将<code>sayName</code>方法添加到构造函数的原型对象上面实现共享：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Person</span>(<span class="params">name,age,job</span>) {</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">name</span> = name;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">age</span> = age;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">job</span> = job;</span><br><span class="line">}</span><br><span class="line"><span class="title class_">Person</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="title function_">sayName</span>() = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">name</span>);</span><br><span class="line">};</span><br></pre></td></tr></tbody></table></figure>
<blockquote>
<p>注意，这里是使用点语法将方法添加到<code>prototype</code>原型对象上面，而不是直接给<code>prototype</code>赋值一个对象，不能这么做的原因在后面会细说。</p>
</blockquote>
<h2 id="constructor属性"><a href="#constructor属性" class="headerlink" title="constructor属性"></a><code>constructor</code>属性</h2><p>默认情况下，所有原型对象自动获得一个名为<code>constructor</code>的属性，这个属性<strong>指回与之关联的构造函数</strong>。上面的例子中，<code>Person.prototype.constructor</code>指回构造函数<code>Person</code>。</p>
<h2 id="Prototype-特性与-proto-属性"><a href="#Prototype-特性与-proto-属性" class="headerlink" title="[[Prototype]]特性与__proto__属性"></a><code>[[Prototype]]</code>特性与<code>__proto__</code>属性</h2><p>任意一个由构造函数实例化的实例对象都有一个<code>__proto__</code>属性，这个属性指向实例对象的构造函数的原型对象。例如前面的例子，<code>person1.__proto__</code>指向<code>Person.prototype</code>。</p>
<p>那么<code>[[Prototype]]</code>特性是什么呢？其实它也是实例对象所有的，它是一个指针。每次调用构造函数创建一个实例时，这个实例的内部<code>[[Prototype]]</code>指针就会被赋值为构造函数的原型对象。但我们并不能直接访问这个特性（指针），所以便有了<code>__proto__</code>属性供我们访问实例对象对应的构造函数的原型对象。</p>
<blockquote>
<p><strong>任意一个构造函数实例化的对象</strong>，<strong>都有一个<strong>proto</strong>属性（<strong>proto</strong>并非标准属性，ECMA-262第5版将该属性或指针称为[[Prototype]]，可通过Object.getPrototypeOf()标准方法访问该属性）</strong>，指向构造函数的原型对象。—-<a target="_blank" rel="noopener" href="http://home.cnblogs.com/u/sinstone/">sinのstone</a></p>
</blockquote>
<h2 id="彻底搞懂prototype、constructor和-proto-之间的关系"><a href="#彻底搞懂prototype、constructor和-proto-之间的关系" class="headerlink" title="彻底搞懂prototype、constructor和__proto__之间的关系"></a>彻底搞懂<code>prototype</code>、<code>constructor</code>和<code>__proto__</code>之间的关系</h2><p>先来看一段代码：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Person</span>(<span class="params">name,age,job</span>) {</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">name</span> = name;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">age</span> = age;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">job</span> = job;</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="title class_">Person</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="title function_">sayName</span>() = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="variable language_">this</span>.<span class="property">name</span>);</span><br><span class="line">};</span><br><span class="line"></span><br><span class="line"><span class="keyword">let</span> <span class="title class_">Junli</span> = <span class="keyword">new</span> <span class="title class_">Person</span>(<span class="string">"君丽"</span>,<span class="number">18</span>,<span class="string">"小阿飞女盆友"</span>)</span><br></pre></td></tr></tbody></table></figure>
<p>基于上面的代码，用一张图来展示<code>prototype</code>、<code>constructor</code>和<code>__proto__</code>之间的关系：</p>
<p><img src="/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/三者关系.png" alt="三者关系"></p>
<h1 id="原型链"><a href="#原型链" class="headerlink" title="原型链"></a>原型链</h1><p>JavaScript查找对象某个属性遵循以下步骤：</p>
<ol>
<li>现在实例对象本身的属性中查找是否有该属性，若有则直接返回该属性值。</li>
<li>若实例对象本身没有该属性，就到该实例对象对应的原型对象中查找，若有则返回该属性值。</li>
<li>若实例的原型对象也没有该属性，则搜索原型对象的原型。</li>
<li>重复第三步知道搜索到<code>Object</code>为止。</li>
</ol>
<p>上面的步骤就是原型链的基本思想</p>
<h1 id="ES5继承"><a href="#ES5继承" class="headerlink" title="ES5继承"></a>ES5继承</h1><h2 id="原型继承"><a href="#原型继承" class="headerlink" title="原型继承"></a>原型继承</h2><p>ES5继承主要是通过构造函数+原型对象实现的，核心原理就是将子类的原型对象赋值为一个父类实例对象，然后再将子类原型对象的<code>constructor</code>属性赋值为子类的构造函数。即<code>Son.prototype = new Father()</code>和<code>Son.prototype.constructor = Son</code>。这样一来，子类便可以使用父类的属性和方法。</p>
<p>假设有一个现在有一个系统，用户和管理员都可以登录系统，但管理员可以删除一个用户，继承关系实现代码如下：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">User</span>(<span class="params">username,password</span>) {</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">username</span> = username;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">password</span> = password;</span><br><span class="line">}</span><br><span class="line"><span class="title class_">User</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">login</span> = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">"登录"</span>);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Admin</span>(<span class="params"></span>) {}</span><br><span class="line"><span class="comment">// 实现继承</span></span><br><span class="line"><span class="title class_">Admin</span>.<span class="property"><span class="keyword">prototype</span></span> = <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line"><span class="title class_">Admin</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">constructor</span> = <span class="title class_">Admin</span>;</span><br><span class="line"><span class="title class_">Admin</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">deletePerson</span> = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">"删除用户"</span>);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> admin = <span class="keyword">new</span> <span class="title class_">Admin</span>(<span class="string">"admin"</span>, <span class="string">"password"</span>);</span><br><span class="line">admin.<span class="title function_">login</span>();</span><br><span class="line">admin.<span class="title function_">deletePerson</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(admin);</span><br></pre></td></tr></tbody></table></figure>
<p>运行结果如下所示：</p>
<p><img src="/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/继承运行结果1.png" alt="继承运行结果1"></p>
<p>可以发现，已经实现了子类调用父类的方法，即<code>Admin</code>实例调用了<code>User</code>的登录方法。但还有个问题，<code>admin</code>和<code>password</code>两个参数并没能传递给父类<code>User</code>，所以导致<code>Admin</code>实例对象的<code>username</code>和<code>password</code>属性为<code>undefined</code>。</p>
<p>为了解决给父类传参问题我们重新定义利用原型继承的步骤：</p>
<ol>
<li>创建父类构造函数，定义父类的属性和方法。</li>
<li>创建子类构造函数，并在构造函数中调用父类构造函数，使用<code>父类.call()</code>绑定当前子类的this到父类构造函数上，确保子类可以继承父类的属性。</li>
<li>创建父类的实例，并将该实例赋值给子类构造函数的prototype，并将子类原型对象的<code>constructor</code>属性赋值为子类的构造函数。</li>
<li>在子类构造函数的原型中添加子类特有的属性和方法。</li>
</ol>
<blockquote>
<p>额外总结一下，一般将属性放在构造函数内，方法放在原型对象中。</p>
</blockquote>
<p>基于上面的步骤我们重写上面的例子：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">User</span>(<span class="params">username,password</span>) {</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">username</span> = username;</span><br><span class="line">    <span class="variable language_">this</span>.<span class="property">password</span> = password;</span><br><span class="line">}</span><br><span class="line"><span class="title class_">User</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">login</span> = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">     <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">"登录"</span>);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Admin</span>(<span class="params">username,password</span>) {</span><br><span class="line">    <span class="title class_">User</span>.<span class="title function_">call</span>(username,password); <span class="comment">// 只改动了这一处</span></span><br><span class="line">}</span><br><span class="line"><span class="comment">// 实现继承</span></span><br><span class="line"><span class="title class_">Admin</span>.<span class="property"><span class="keyword">prototype</span></span> = <span class="keyword">new</span> <span class="title class_">User</span>();</span><br><span class="line"><span class="title class_">Admin</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">constructor</span> = <span class="title class_">Admin</span>;</span><br><span class="line"><span class="title class_">Admin</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">deletePerson</span> = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">    <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">"删除用户"</span>);</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="keyword">const</span> admin = <span class="keyword">new</span> <span class="title class_">Admin</span>(<span class="string">"admin"</span>, <span class="string">"password"</span>);</span><br><span class="line">admin.<span class="title function_">login</span>();</span><br><span class="line">admin.<span class="title function_">deletePerson</span>();</span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(admin);</span><br></pre></td></tr></tbody></table></figure>
<p>运行结果如下：</p>
<p><img src="/2023/07/16/JavaScript%EF%BC%9A%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0%E4%B8%8E%E5%8E%9F%E5%9E%8B%E3%80%81%E5%8E%9F%E5%9E%8B%E9%93%BE/继承运行结果2.png" alt="继承运行结果2"></p>
<h2 id="原型继承的主要问题"><a href="#原型继承的主要问题" class="headerlink" title="原型继承的主要问题"></a>原型继承的主要问题</h2><p>上面所说的原型继承有一个致命问题，<strong>继承过来的实例属性，如果是引用类型，会被多个子类的实例共享</strong>，这意味着所有的子类实例对于该属性的修改都会影响到其他子类实例。这是因为引用类型的属性存储在堆内存中，并且多个实例共用同一个引用地址。</p>
<p>用一个例子来看这个问题：</p>
<figure class="highlight javascript"><table><tbody><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">function</span> <span class="title function_">Person</span>(<span class="params">name</span>) {</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">name</span> = name;</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">hobbies</span> = [<span class="string">'reading'</span>, <span class="string">'swimming'</span>];</span><br><span class="line">}</span><br><span class="line"></span><br><span class="line"><span class="title class_">Person</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">sayHello</span> = <span class="keyword">function</span>(<span class="params"></span>) {</span><br><span class="line">  <span class="variable language_">console</span>.<span class="title function_">log</span>(<span class="string">'Hello, my name is '</span> + <span class="variable language_">this</span>.<span class="property">name</span>);</span><br><span class="line">};</span><br><span class="line"></span><br><span class="line"><span class="keyword">function</span> <span class="title function_">Student</span>(<span class="params">name, grade</span>) {</span><br><span class="line">  <span class="title class_">Person</span>.<span class="title function_">call</span>(<span class="variable language_">this</span>,name);</span><br><span class="line">  <span class="variable language_">this</span>.<span class="property">grade</span> = grade;</span><br><span class="line">}</span><br><span class="line"><span class="title class_">Student</span>.<span class="property"><span class="keyword">prototype</span></span> = <span class="keyword">new</span> <span class="title class_">Person</span>();</span><br><span class="line"><span class="title class_">Student</span>.<span class="property"><span class="keyword">prototype</span></span>.<span class="property">constructor</span> = <span class="title class_">Student</span></span><br><span class="line"></span><br><span class="line"><span class="keyword">var</span> student1 = <span class="keyword">new</span> <span class="title class_">Student</span>(<span class="string">'Alice'</span>, <span class="number">5</span>);</span><br><span class="line"><span class="keyword">var</span> student2 = <span class="keyword">new</span> <span class="title class_">Student</span>(<span class="string">'Bob'</span>, <span class="number">6</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">// 修改student1的hobbies</span></span><br><span class="line">student1.<span class="property">hobbies</span>.<span class="title function_">push</span>(<span class="string">'playing basketball'</span>);</span><br><span class="line"></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(student1.<span class="property">hobbies</span>);  <span class="comment">// ['reading', 'swimming', 'playing basketball']</span></span><br><span class="line"><span class="comment">// 影响了student2的hobbies</span></span><br><span class="line"><span class="variable language_">console</span>.<span class="title function_">log</span>(student2.<span class="property">hobbies</span>);  <span class="comment">// ['reading', 'swimming', 'playing basketball']</span></span><br></pre></td></tr></tbody></table></figure>
<p>上面例子中修改<code>student1</code>的<code>hobbies</code>属性影响到了<code>student2</code>的<code>hobbies</code>属性。</p>
<p>为了解决上面的问题，可以使用其他的解决方式或继承方式，比如<strong>盗用构造函数</strong>、<strong>原型继承</strong>、<strong>组合继承</strong>、<strong>寄生组合继承</strong>等，这些方式避免了引用类型属性被共享的问题。这些方式以后再补充。</p>
<blockquote>
<p>本文引用下列文章：</p>
<p><a target="_blank" rel="noopener" href="https://blog.csdn.net/jieyucx/article/details/131445345"> javascript原型、原型链、继承详解_js 原型链继承</a></p>
</blockquote>

    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/JavaScript%E5%9F%BA%E7%A1%80-%E6%9E%84%E9%80%A0%E5%87%BD%E6%95%B0-%E5%8E%9F%E5%9E%8B-%E5%8E%9F%E5%9E%8B%E9%93%BE/" rel="tag"># -JavaScript基础 -构造函数 -原型 -原型链</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2023/07/14/JavaScript%EF%BC%9A%E5%87%BD%E6%95%B0/" rel="prev" title="JavaScript：函数">
                  <i class="fa fa-chevron-left"></i> JavaScript：函数
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2023/07/20/Vue%E5%85%A5%E9%97%A8%E7%AC%94%E8%AE%B0/" rel="next" title="Vue入门笔记">
                  Vue入门笔记 <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">鸣蜩十七</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/muse/" rel="noopener" target="_blank">NexT.Muse</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>
  <div class="sidebar-dimmer"></div>
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up fa-lg"></i>
    <span>0%</span>
  </div>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/schemes/muse.js"></script><script src="/js/next-boot.js"></script>

  




  




  

  <script class="next-config" data-name="enableMath" type="application/json">true</script><script class="next-config" data-name="mathjax" type="application/json">{"enable":true,"tags":"none","js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mathjax/3.2.2/es5/tex-mml-chtml.js","integrity":"sha256-MASABpB4tYktI2Oitl4t+78w/lyA+D7b/s9GEP0JOGI="}}</script>
<script src="/js/third-party/math/mathjax.js"></script>



</body>
</html>
